package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.ArticleBehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * ClassName: ApLikeBehaviorServiceImpl
 * Description:
 * date: 2023/8/27 0027 16:33
 *
 * @author zHan
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 阅读
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        // 检查参数
        checkParam(dto);
        // 获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        // 获得read的key
        String readKey =
                ArticleBehaviorConstants.READ + user.getId() + ":" + dto.getArticleId();
        // 获取redis
        String countStr = cacheService.get(readKey);
        if (countStr == null) {
            // 第一次阅读
            String value = JSON.toJSONString(dto);
            cacheService.set(readKey, value);
        } else {
            // 之后的阅读
            Map map = JSON.parseObject(countStr, Map.class);
            int count = (int) map.get("count");
            count += dto.getCount();
            dto.setCount(count);
            String value = JSON.toJSONString(dto);
            cacheService.set(readKey, value);
        }
        // 封装对象
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        updateArticleMess.setAdd(1);
        // 发送消息，数据聚合
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,
                JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查参数
     *
     * @param dto
     */
    private void checkParam(ReadBehaviorDto dto) {
        if (dto.getArticleId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getCount() < 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
